import * as ActionTypes from './ActionTypes.js';

let nextTodoId = 0;

export const reducer = (state=[] , action) =>{
    switch(action.type){
        case ActionTypes.ADD_TODO:
            return [
                ...state,
                {
                    id: nextTodoId++,
                    text: action.text,
                    place: action.place,
                    time: action.time,
                    complete: false,
                    active: false,
                    index:state.length
                }
            ];


        case ActionTypes.DELETE_TODO:
            let delState = state;
            for(let i=delState.length-1 ;i>=0 ;i--){
                if(delState[i].active === true){
                    delState.splice(i , 1);
                }
            }
            for(let i=0; i<delState.length; i++){
                delState[i].index = i;
            }
            return delState;


        case ActionTypes.MOD_TODO:
            return state.map((item)=>{
               if(item.active === true){
                   return Object.assign({}, item, {
                        text:action.text,
                        place:action.place,
                        time:action.time
                   });
               }else{
                   return item;
               }
            });

        case ActionTypes.COMPLETE_TODO:
            return state.map((item)=>{
               if(item.active === true){
                   return Object.assign({}, item, {complete: true});
               }else{
                   return item;
               }
            });


        case ActionTypes.ACTIVE_TODO:
            return state.map((item)=>{
                if(item.index === action.index){
                    return Object.assign({}, item, {active: !item.active});
                }else{
                    return item;
                }
            });


        default:
            return state;
    }
};